//
//  PopMenuView.swift
//  
//
//  Created by 孙长坦 on 2022/9/1.
//

import Foundation
import UIKit

open class PopMenuView: UITableView {
    var menuDatas: [MenuData]
    
    public var onMenuTap: ((_ menuData: MenuData?) -> Void)?
    
    public init(frame: CGRect, menuDatas: [MenuData]) {
        self.menuDatas = menuDatas

        super.init(frame: frame, style: .plain)
        
        register(UITableViewCell.self, forCellReuseIdentifier: "PopMenuView")
        
        rowHeight = 50
        separatorInset = .zero
        
        dataSource = self
        delegate = self
    }
    
    required public init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

extension PopMenuView: UITableViewDataSource {
    public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return menuDatas.count
    }
    
    public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "PopMenuView", for: indexPath)
        
        cell.textLabel?.font = UIFont.systemFont(ofSize: 16)
        cell.textLabel?.text = menuDatas[indexPath.row].title
        cell.textLabel?.textColor = UIColor.black
        
        return cell
    }
}

extension PopMenuView: UITableViewDelegate {
    public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        
        onMenuTap?(menuDatas[indexPath.row])
    }
}
